<template>
  <div class="app-container-trans">
    <div class="tree_control">
      <div class="title">{{ $t('organization.org') }}</div>
      <el-tree ref="way_tree" :data="roleTree" node-key="id" default-expand-all :expand-on-click-node="false" @node-click="nodeClick" />
    </div>
    <div class="container">
      <el-form ref="formSearch" :model="searchForm" label-width="100px">
        <el-row>
          <el-col :span="19">
            <el-row class="form_table">
              <el-col :span="8">
                <el-form-item :label="$t('role.roleName')" prop="roleName">
                  <el-input v-model.trim="searchForm.roleName" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('role.remark')" prop="remark">
                  <el-input v-model.trim="searchForm.remark" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('businessGlossary.enabled')" prop="enabled">
                  <el-select v-model="searchForm.enabled" :placeholder="$t('placeholder.select')" clearable>
                    <el-option v-for="item in $enableDict" :key="item.id" :label="item.text" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="5" style="text-align: center">
            <el-button
              type="primary"
              @click="
                searchForm.pageNumber = 1
                getData()
              "
            >{{ $t('btn.query') }}</el-button>
            <el-button type="danger" @click="resetForm('formSearch')">{{ $t('btn.reset') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-button v-permission="'gaeaRoleController#insert'" type="primary" icon="el-icon-plus" @click="openCreateUser">{{ $t('btn.add') }}</el-button>
      <el-button v-permission="'gaeaRoleController#update'" type="primary" icon="el-icon-edit" :disabled="selectedList.length != 1" @click="editDetail('edit', null)">{{ $t('btn.edit') }}</el-button>
      <el-button v-permission="'gaeaRoleController#deleteById'" type="primary" icon="el-icon-edit" :disabled="selectedList.length != 1" @click="setMenu">{{ $t('role.setPermission') }}</el-button>
      <delete-btn v-permission="'gaeaRoleController#roleAuthorities'" :disabled="selectedList.length < 1" @handleDelete="handleDelete" />
      <el-table stripe :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="50" center />
        <el-table-column :label="$t('role.roleName')" align="center" min-width="180">
          <template slot-scope="scope">
            <span class="view" @click="editDetail('view', scope.row)">{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="roleCode" :label="$t('role.roleCode')" align="center" min-width="160" />
        <el-table-column prop="remark" :label="$t('role.remark')" align="center" min-width="160" />
        <el-table-column prop="enabled" :label="$t('businessGlossary.enabled')" min-width="90" align="center">
          <template slot-scope="scope">
            <span>{{ $t(`businessGlossary.enabled${scope.row.enabled}`) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('businessGlossary.creationTime')" align="center" min-width="160" />
        <el-table-column prop="createByView" :label="$t('businessGlossary.creator')" align="center" min-width="160" />
        <el-table-column prop="updateTime" :label="$t('businessGlossary.modifyTime')" align="center" min-width="180" />
        <el-table-column prop="updateByView" :label="$t('businessGlossary.modifyUser')" align="center" min-width="140" />
      </el-table>
      <el-pagination v-show="total > 0" background :current-page.sync="searchForm.pageNumber" :page-sizes="$pageSizeAll" :page-size="searchForm.pageSize" layout="total, prev, pager, next, jumper, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog :title="$t(`btn.${dialogTittle}`)" width="60%" :close-on-click-modal="false" center :visible.sync="userDialog" @close="closeDialog">
      <el-form ref="roleForm" :model="dialogForm" :rules="userFormRules" label-width="110px" style="padding-right: 15px" :disabled="dialogTittle == 'view'">
        <el-row class="form_table">
          <el-col :span="12">
            <el-form-item :label="$t('role.roleCode')" prop="roleCode">
              <el-input v-model.trim="dialogForm.roleCode" clearable :disabled="dialogTittle != 'add'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.roleName')" prop="roleName">
              <el-input v-model.trim="dialogForm.roleName" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.orgCode')" prop="orgCode">
              <el-select v-model="dialogForm.orgCode" :placeholder="$t('placeholder.select')" :disabled="dialogTittle != 'add'" clearable>
                <el-option v-for="item in orgParentList" :key="item.orgCode" :label="item.orgName" :value="item.orgCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.remark')" prop="remark">
              <el-input v-model.trim="dialogForm.remark" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('businessGlossary.enabled')" prop="enabled">
              <el-select v-model="dialogForm.enabled" :placeholder="$t('placeholder.select')" clearable>
                <el-option v-for="item in $enableDict" :key="item.id" :label="item.text" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button v-if="dialogTittle != 'view'" type="primary" plain @click="UserConfirm">{{ $t('btn.confirm') }}</el-button>
        <el-button type="danger" plain @click="userDialog = false">{{ $t('btn.close') }}</el-button>
      </div>
    </el-dialog>
    <!-- <role-org :id="id" :visib="orgDialog" @handleClose="orgDialog = false" /> -->
    <role-menu :org-code="orgCode" :role-code="roleCode" :visib="menuDialog" @handleClose="menuDialog = false" />
    <!-- <role-auth :id="id" :visib="authDialog" @handleClose="authDialog = false" /> -->
  </div>
</template>
<script>
import { getRoleList, addRole, editRole, deleteRoles } from '@/api/authority'
import { getParentOrgList, getOrgTree } from '@/api/organization'
export default {
  name: 'Role',
  components: {
    RoleMenu: require('./components/RoleMenu').default,
    // RoleOrg: require('./components/RoleOrg').default,
    // RoleAuth: require('./components/RoleAuth').default,
  },
  data() {
    return {
      orgParentList: [], // 组织下拉列表
      roleTree: [],
      orgDialog: false,
      menuDialog: false,
      // authDialog: false,
      orgCode: '',
      roleCode: '',
      selectedList: [],
      searchForm: {
        remark: '',
        roleName: '',
        enabled: '',
        code: null,
        pageSize: 10,
        pageNumber: 1,
      },
      tableList: [],
      total: 0,
      dialogTittle: 'view',
      userDialog: false,
      dialogForm: {
        remark: '', // 描述
        menuIds: [], // 菜单id
        roleCode: '', // 角色代码
        orgCode: '', // 所属机构
        roleName: '', // 角色名称
        enabled: 1, // 状态
      },
      userFormRules: {
        roleCode: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        roleName: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        orgCode: [{ required: true, message: this.$t('placeholder.select'), trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getTree()
    this.getData()
    this.getParentOrg()
  },
  methods: {
    // 点击tree节点时 将tree的id作为上级机构代码 查询列表
    nodeClick(d) {
      this.searchForm.code = d.id
      this.dialogForm.orgCode = d.id
      this.getData()
    },
    // 获取侧边树结构
    async getTree() {
      const { code, data } = await getOrgTree()
      if (code != '200') return
      this.roleTree = data
    },
    // 获取系统机构（组织就是机构）
    async getParentOrg() {
      const { code, data } = await getParentOrgList()
      if (code != '200') return
      this.orgParentList = data
    },
    // 分配组织
    setOrg() {
      this.id = this.selectedList[0].roleCode
      this.orgDialog = true
    },
    setMenu() {
      this.roleCode = this.selectedList[0].roleCode
      this.orgCode = this.selectedList[0].orgCode
      this.menuDialog = true
    },
    // setAuth() {
    //   this.id = this.selectedList[0].roleCode
    //   this.authDialog = true
    // },
    // 提交
    UserConfirm() {
      this.$refs.roleForm.validate(async(valid, obj) => {
        if (valid) {
          if (this.dialogTittle == 'add') {
            const { code } = await addRole(this.dialogForm)
            if (code != '200') return
            this.closeDialog(true)
          } else {
            const { code } = await editRole(this.dialogForm)
            if (code != '200') return
            this.closeDialog(true)
          }
        } else {
          return
        }
      })
    },
    closeDialog(bool) {
      bool && this.getData()
      this.checkedKeys = []
      this.$refs['roleForm'].resetFields()
      this.userDialog = false
    },
    // 删除操作 做 提示
    async handleDelete() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await deleteRoles(ids)
      if (code != '200') return
      this.getData()
    },
    // 新建操作
    openCreateUser() {
      this.dialogTittle = 'add' // 新建
      this.userDialog = true
    },

    // 编辑和查看操作
    editDetail(title, row) {
      this.dialogTittle = title

      this.userDialog = true
      this.$nextTick(() => {
        this.dialogForm = JSON.parse(JSON.stringify(row || this.selectedList[0]))
        // 赋值到权限列表绑定的list上
        // 将菜单非叶子节点的menuId过滤出来
        // this.deleteParentMenuIds(this.getCheckedId())
      })
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.tableList = []
      this.total = 0
      this.getData()
    },
    // 查询
    async getData() {
      const { data, code } = await getRoleList(this.searchForm)
      if (code != '200') return
      this.tableList = data.records
      this.total = data.total
    },
    // 选择项改变时
    handleSelectionChange(val) {
      this.selectedList = val
    },
    // 页码改变
    handleCurrentChange(pageNumber) {
      this.searchForm.pageNumber = pageNumber
      this.getData()
    },
    // 每页size改变时
    handleSizeChange(val) {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = val
      this.getData()
    },
  },
}
</script>
